﻿using Castle.Core.Logging;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentAgriculture.Services
{
    public class PermissionService : IPermissionService
    {
        /// <summary>
        /// 权限仓储
        /// </summary>
        private readonly IPermissionRepository _permissionRepository;
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly AgricultureDbContext _db;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<PermissionService> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="permissionRepository">权限仓储</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="logger">日志</param>
        public PermissionService(IPermissionRepository permissionRepository, AgricultureDbContext db, ILogger<PermissionService> logger)
        {
            _permissionRepository = permissionRepository;
            _db = db;
            _logger = logger;
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public List<MenuOutput> GetMenuList(int pid)
        {
            var list = _permissionRepository.GetPermission(pid).ToList();
            var menuList = list.Select(p => new MenuOutput()
            {
                value = p.Perid,
                label = p.PerName,
                PermissionUrl = p.PerUrl,
                Children = GetMenuList(p.Perid).Count() > 0 ? GetMenuList(p.Perid) : null
            }).ToList();
            return menuList;
        }
        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<List<Permission>> GetRolePermission(int roleId)
        {
            //找到该角色
            var role = await _permissionRepository.GetRolePermission(roleId);
            var list = from rp in _db.Rolepermissions
                       join p in _db.Permissions
                       on rp.Perid equals p.Perid
                       where rp.Rid == roleId
                       select new Permission()
                       {
                           Perid = p.Perid
                       };
            return list.ToList();
            //var ids = new List<int>();
            //foreach (var item in list)
            //{
            //    ids.Add(item.Perid);
            //}
            ////获取角色权限
            //var rplist = from rp in _db.Rolepermissions
            //             join p in _db.Permissions
            //             on rp.Perid equals p.Perid
            //             where rp.Rid == roleId
            //             select new RolesPermissionOutput()
            //             {
            //                 Pid = ids
            //             };
            //return rplist.ToList();
        }
        /// <summary>
        /// 修改角色权限
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int SavePermission(UpdRolePermissionInput input)
        {
            using (var tran = _db.Database.BeginTransaction())
            {
                try
                {
                    var rolepermission = _db.Rolepermissions.Where(p => p.Rid == input.RoleId);
                    _db.RemoveRange(rolepermission);
                    foreach (var item in input.PerId)
                    {
                        var entity = new Rolepermission()
                        {
                            Rid = input.RoleId,
                            Perid = item
                        };
                        _db.Rolepermissions.Add(entity);
                    }
                    _db.SaveChanges();
                    tran.Commit();
                    return 1;
                }
                catch (Exception ex)
                {
                    _logger.LogError("修改角色权限失败" + ex.Message);
                    tran.Rollback();
                    throw;
                }
            }
        }
    }
}